/**
 * 
 */
package com.rhf.core.db.implementations;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.rhf.core.commons.logging.AppLog;
import com.rhf.core.commons.logging.AppLogManager;
import com.rhf.core.commons.properties.PropertiesManager;

/**
 * @author fabiensaulnier
 * 
 */
public class Base {

	/**
	 * Nom par d�faut du datasource
	 */
	public static final String NOM_DATASOURCE_DEFAUT = "jdbc/postgres";

	// get database logger
	protected AppLog appLog = AppLogManager.getDbLogger();

	/**
	 * get the connection
	 * 
	 * @return the connection
	 */
	protected Connection getConnection() {

		// get the database from properties file
		String datasourceName = PropertiesManager.getProperties().getString(
				"DB_DATASOURCE_NOM", NOM_DATASOURCE_DEFAUT);

		// get the connection follow the datasource
		return this.getConnection(datasourceName);
	}

	/**
	 * get the connection
	 * 
	 * @param datasourceName
	 * @return the connection
	 */
	protected Connection getConnection(final String datasourceName) {

		Connection conn = null;

		try {
			this.appLog
					.debug("the datasource used is [" + datasourceName + "]");
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource) envContext.lookup(datasourceName);
			conn = ds.getConnection();

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return conn;
	}

	/**
	 * close all database resources
	 * 
	 * @param rs
	 * @param stmt
	 * @param conn
	 */
	protected void closeResources(final ResultSet rs, final Statement stmt,
			final Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}

			if (stmt != null) {
				stmt.close();
			}

			if (conn != null) {
				conn.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * get the current database time
	 * 
	 * @return the current database time
	 */
	public static java.sql.Date getCurrentJavaSqlDate() {
		java.util.Date today = new java.util.Date();

		return new java.sql.Date(today.getTime());
	}

	/**
	 * get the current database timestamp
	 * 
	 * @return the current database timestamp
	 */
	public static java.sql.Timestamp getCurrentJavaSqlTimestamp() {
		java.util.Date today = new java.util.Date();

		return new java.sql.Timestamp(today.getTime());
	}

}
